from flask import Blueprint,jsonify,request
from app.mapper.database import db,UserInfo
from app.service.userservice import UserService

user_bp = Blueprint('user',__name__)
userService = UserService()

@user_bp.route('/login',methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    res = userService.login(username,password)

    return jsonify(res)

@user_bp.route('/checkname',methods=['POST'])
def checkname():
    data = request.get_json()
    username= data.get('username')

    res = userService.checkname(username)

    return jsonify(res)

# 查询用户
@user_bp.route('/selectusers',methods=['GET'])
def selectAll():
    # userInfo = userService.select_all_users()
    page = int(request.args.get('page'))
    # print(page)
    # print(type(page))
    json_data = userService.select_all_user(page)

    return jsonify(json_data)

# 添加用户
@user_bp.route('/adduser',methods=['POST'])
def add_user():
    data = request.get_json()
    userid = int(data.get('userid'))
    username= data.get('username')
    password = data.get('password')
    role = data.get('role')
    user = UserInfo(username,password,role)
    user.set_userid(userid)

    res = userService.add_user(user)

    return jsonify(res)

# 删除用户
@user_bp.route('/deleteuser',methods=['GET'])
def delete_user():
    userid = int(request.args.get('UserID'))
    res = userService.deelete_by_id(userid)

    return jsonify(res)

# 修改用户
@user_bp.route('/edituser',methods=['POST'])
def edit_user():
    data = request.get_json()
    userid = data.get('userid')

    username = data.get('username')
    password = data.get('password')
    role = data.get('role')
    
    user = UserInfo(username,password,role)
    user.set_userid(userid)
    res = userService.edit_user(user)

    return jsonify(res)